<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="会员名称" prop="memberName">
        <el-input
          v-model="queryParams.memberName"
          placeholder="请输入会员名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="reviewsList">
      <el-table-column label="商品名称" align="center" prop="productName" />
      <el-table-column label="会员名称" align="center" prop="memberName" />
      <el-table-column label="评价" align="center" prop="reviewContent">
        <template #default="scope">
          <span :class="getReviewClass(scope.row.reviewContent)">
            {{ scope.row.reviewContent || '系统默认好评' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="物流评分" align="center" prop="logisticsScore" />
      <el-table-column label="服务评分" align="center" prop="serviceScore" />
      <el-table-column label="描述评分" align="center" prop="descriptionScore" />
      <el-table-column label="评价时间" align="center" prop="reviewTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.reviewTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="页面展示" align="center" prop="isDisplay">
        <template #default="scope">
          <el-switch
            v-model="scope.row.isDisplay"
            :active-value="1"
            :inactive-value="0"
            active-text="展示"
            inactive-text=""
            @change="handleDisplayChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleView(scope.row)" v-hasPermi="['huiyuan:reviews:query']">查看详情</el-button>
          <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['huiyuan:reviews:remove']">删除评价</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 评价详情对话框 -->
    <el-dialog 
      :title="`${reviewDetail.memberName || '用户'}的评价详情`" 
      v-model="detailOpen" 
      width="600px" 
      append-to-body
      :close-on-click-modal="false"
    >
      <div class="review-detail-container">
        <!-- 评价信息区域 -->
        <div class="review-info-section">
          <div class="product-info">
            <div class="product-image">
              <el-image 
                :src="reviewDetail.productImage || 'https://via.placeholder.com/120x120?text=商品图片'" 
                fit="cover"
                style="width: 120px; height: 120px; border-radius: 8px;"
              />
            </div>
            <div class="product-details">
              <div class="product-name">{{ reviewDetail.productName || '测试sqai 110' }}</div>
              <div class="store-name">店铺名称: {{ reviewDetail.shopName || '杂货铺' }}</div>
              <div class="order-number">订单号: {{ reviewDetail.dingdanId || '0202507121943839961728176129' }}</div>
              <div class="reviewer-info">
                <el-icon class="user-icon"><User /></el-icon>
                <span>{{ reviewDetail.memberName || '微信用户' }}</span>
              </div>
            </div>
          </div>
          
          <!-- 评价内容 -->
          <div class="review-content">
            <div class="content-label">评价内容:</div>
            <div class="content-text">{{ reviewDetail.reviewContent || '系统默认好评' }}</div>
          </div>
        </div>

        <!-- 评分区域 -->
        <div class="ratings-section">
          <div class="rating-item">
            <span class="rating-label">物流评分:</span>
            <span class="rating-value">{{ reviewDetail.logisticsScore || 5 }}分</span>
          </div>
          <div class="rating-item">
            <span class="rating-label">服务评分:</span>
            <span class="rating-value">{{ reviewDetail.serviceScore || 5 }}分</span>
          </div>
          <div class="rating-item">
            <span class="rating-label">描述评分:</span>
            <span class="rating-value">{{ reviewDetail.descriptionScore || 5 }}分</span>
          </div>
        </div>

        <!-- 页面展示控制 -->
        <div class="display-control">
          <span class="control-label">页面展示:</span>
          <el-switch
            v-model="reviewDetail.isDisplay"
            :active-value="1"
            :inactive-value="0"
            active-text="展示"
            inactive-text=""
            @change="handleDetailDisplayChange"
          />
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailOpen = false">取消</el-button>
          <el-button type="primary" @click="confirmDetailChange">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Reviews">
import {delReviews, listReviews} from "@/api/huiyuan/reviews"
import request from '@/utils/request'

const { proxy } = getCurrentInstance()

const reviewsList = ref([])
const loading = ref(true)
const showSearch = ref(true)
const total = ref(0)

// 详情对话框相关变量
const detailOpen = ref(false)
const reviewDetail = ref({})

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    memberName: null
  }
})

const { queryParams } = toRefs(data)

/** 查询会员评价列表 */
function getList() {
  loading.value = true
  listReviews(queryParams.value).then(response => {
    reviewsList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 处理页面展示状态变化 */
function handleDisplayChange(row) {
  const status = row.isDisplay
  
  // 同步更新详情对话框中的展示状态（如果对话框已打开且是同一行数据）
  if (detailOpen.value && reviewDetail.value.id === row.id) {
    reviewDetail.value.isDisplay = status
  }
  
  // 暂时注释掉API调用，用于测试按钮功能
  // updateReviewStatus(row.id, status).then(() => {
  //   proxy.$modal.msgSuccess(`修改成功`)
  // }).catch(() => {
  //   row.isDisplay = status === 1 ? 0 : 1 // 恢复原始状态
  // })
  
  // 测试用：直接显示成功提示
  proxy.$modal.msgSuccess(`测试：状态已切换为${status === 1 ? '展示' : '不展示'}`)
  console.log('测试按钮点击，当前状态:', status, '行数据:', row)
}

/** 更新评价页面展示状态 - 暂时注释 */
function updateReviewStatus(id, status) {
  return new Promise((resolve, reject) => {
    // 暂时注释掉API调用
    // updateReview({ id, isDisplay: status }).then(response => {
    //   resolve(response)
    // }).catch(error => {
    //   reject(error)
    // })
    
    // 测试用：模拟成功响应
    setTimeout(() => {
      console.log('模拟API调用成功，ID:', id, '状态:', status)
      resolve({ code: 200, msg: 'success' })
    }, 500)
  })
}

/** 更新评价 - 暂时注释 */
function updateReview(data) {
  // 暂时注释掉API调用
  // return request({
  //   url: '/huiyuan/reviews/update',
  //   method: 'put',
  //   data: data
  // })
  
  // 测试用：返回模拟响应
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({ code: 200, msg: 'success' })
    }, 300)
  })
}

/** 查看评价详情 */
function handleView(row) {
  // 暂时注释掉API调用，用于测试
  // getReviews(row.id).then(response => {
  //   reviewDetail.value = response.data
  //   detailOpen.value = true
  // })
  
  // 测试用：直接显示详情信息
  reviewDetail.value = {
    ...row,
    productImage: 'https://via.placeholder.com/120x120?text=商品图片',
    shopName: '杂货铺',
    dingdanId: '0202507121943839961728176129'
  }
  detailOpen.value = true
  console.log('查看评价详情:', row)
}

/** 处理详情对话框中的展示状态变化 */
function handleDetailDisplayChange() {
  console.log('详情对话框中的展示状态变化:', reviewDetail.value.isDisplay)
  
  // 同步更新表格中对应行的展示状态
  const tableRow = reviewsList.value.find(item => item.id === reviewDetail.value.id)
  if (tableRow) {
    tableRow.isDisplay = reviewDetail.value.isDisplay
  }
  
  // 测试用：显示同步提示
  proxy.$modal.msgSuccess(`测试：详情和表格状态已同步为${reviewDetail.value.isDisplay === 1 ? '展示' : '不展示'}`)
}

/** 确认详情对话框的修改 */
function confirmDetailChange() {
  // 暂时注释掉API调用，用于测试
  // updateReview(reviewDetail.value).then(() => {
  //   proxy.$modal.msgSuccess("修改成功")
  //   detailOpen.value = false
  //   getList() // 刷新列表
  // })
  
  // 测试用：直接显示成功提示
  proxy.$modal.msgSuccess("测试：详情修改成功")
  detailOpen.value = false
  console.log('确认详情修改:', reviewDetail.value)
}

/** 删除评价 */
function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除该评价？').then(function() {
    return delReviews(row.id)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {
    proxy.$modal.msg("取消删除")
  })
}

/** 根据评价内容获取评价类名 */
function getReviewClass(content) {
  if (content && content.includes('好评')) {
    return 'good-review'
  } else if (content && content.includes('差评')) {
    return 'bad-review'
  } else {
    return ''
  }
}

getList()
</script>

<style scoped>
.review-detail-container {
  padding: 20px 0;
}

.review-info-section {
  margin-bottom: 24px;
}

.product-info {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
}

.product-details {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.product-name {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.store-name, .order-number {
  font-size: 14px;
  color: #606266;
}

.reviewer-info {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  color: #909399;
}

.user-icon {
  font-size: 16px;
}

.review-content {
  margin-top: 16px;
}

.content-label {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
}

.content-text {
  font-size: 14px;
  color: #606266;
  line-height: 1.6;
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 6px;
}

.ratings-section {
  margin-bottom: 24px;
}

.rating-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #ebeef5;
}

.rating-item:last-child {
  border-bottom: none;
}

.rating-label {
  font-size: 14px;
  color: #606266;
}

.rating-value {
  font-size: 14px;
  font-weight: 600;
  color: #409eff;
}

.display-control {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px 0;
  border-top: 1px solid #ebeef5;
}

.control-label {
  font-size: 14px;
  color: #606266;
}

.dialog-footer {
  text-align: right;
}

/* 评价内容样式 */
.good-review {
  color: #67c23a; /* 好评颜色 */
  font-weight: bold;
  border: 1px solid #67c23a; /* 好评边框 */
  padding: 2px 6px;
  border-radius: 4px;
  background-color: rgba(103, 194, 58, 0.1); /* 淡绿色背景 */
}

.bad-review {
  color: #f56c6c; /* 差评颜色 */
  font-weight: bold;
  border: 1px solid #f56c6c; /* 差评边框 */
  padding: 2px 6px;
  border-radius: 4px;
  background-color: rgba(245, 108, 108, 0.1); /* 淡红色背景 */
}
</style>
